package com.yuanhua.sim.service.impl;

import com.yuanhua.sim.config.AppConfiguration;
import com.yuanhua.sim.netty.utils.NettyAttrUtil;
import com.yuanhua.sim.netty.utils.SessionUtils;
import com.yuanhua.sim.service.HreatBeatService;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class HreatBeatServiceImpl implements HreatBeatService {
    @Autowired
    private AppConfiguration appConfiguration;

    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate redisTemplate;

    /**
     * 执行心跳异常任务
     * @param ctx
     */
    @Override
    public void process(ChannelHandlerContext ctx) {
        Long heartBeatTime = appConfiguration.getHeartBeatTime() * 1000;
        Long lastReaderTime = NettyAttrUtil.getReaderTime(ctx.channel());
        long now = System.currentTimeMillis();
        if (lastReaderTime != null && now - lastReaderTime > heartBeatTime) {
            //通知下线
            downLine(ctx);
            //关闭连接
            log.info("关闭连接----");
            ctx.channel().close();
        }
    }

    /**
     * 下线
     * @param ctx
     */
    private void downLine(ChannelHandlerContext ctx) {
        Long userId = SessionUtils.getUserId(ctx.channel());
        if (userId != null) {
            log.warn("客户端心跳超时， 需要关闭连接");
        }
//        redisTemplate.delete(String.valueOf(userId));
        SessionUtils.removeChannel(userId);
    }
}
